#!/bin/bash
###SHELLPACK preamble openfoam-bench OpenFOAM-v1812

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargBindings
###SHELLPACK parseargParam --max-cpus	OPENFOAM_MAXCPUS
###SHELLPACK parseargParam --model	OPENFOAM_MODEL
###SHELLPACK parseargParam --iterations	OPENFOAM_ITERATIONS
###SHELLPACK parseargParam --xdiv	OPENFOAM_XDIVISION
###SHELLPACK parseargParam --ydiv	OPENFOAM_YDIVISION
###SHELLPACK parseargParam --zdiv	OPENFOAM_ZDIVISION
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

# Install openmpi requirements
###SHELLPACK mpi_setup_deps OPENFOAM_OPENMPI_VERSION
###SHELLPACK mpi_setup_env OPENFOAM_OPENMPI_VERSION OPENFOAM_MPI_PATH OPENFOAM_MPI_LIBPATH OPENFOAM_MPI_OPTS
###SHELLPACK mpi_setup_shmem

# Versions set in ThirdParty repository, not built through mmtests.
# If this was to be built through mmtests then modify the etc/config.sh/FOO
# files (e.g. etc/config.sh/CGAL) to set version (e.g. fftw-system) and paths
export THIRDPARTY_KAHIP_VERSION="2.12"
export THIRDPARTY_SCOTCH_VERSION="6.0.9"

export BOOST_VERSION="1_66_0"
export CGAL_VERSION="4.12.2"
export FFTW_VERSION="3.3.7"
export GMP_VERSION="6.1.2"
export METIS_VERSION="5.1.0"
export MPFR_VERSION="4.0.1"

export FOAM_VERBOSE="yes"

# CGAL dependencies
###SHELLPACK check_external_install_required boostbuild     boostbuild-${BOOST_VERSION}         ${BOOST_VERSION}
###SHELLPACK check_external_install_required gmpbuild       gmpbuild-${GMP_VERSION}             ${GMP_VERSION}
###SHELLPACK check_external_install_required mpfrbuild      mpfrbuild-${MPFR_VERSION}           ${MPFR_VERSION}
###SHELLPACK check_external_install_required cgalbuild      cgalbuild-${CGAL_VERSION}           ${CGAL_VERSION}

# openfoam dependencies
###SHELLPACK check_external_install_required fftwbuild      fftwbuild-${FFTW_VERSION}           ${FFTW_VERSION}
###SHELLPACK check_external_install_required metisbuild     metisbuild-${METIS_VERSION}         ${METIS_VERSION}

###SHELLPACK check_install_required openfoam-${VERSION}
###SHELLPACK init_complete

cd $SHELLPACK_SOURCES/openfoam-$VERSION-installed/ || die "Failed to cd to openfoam installation directory"
source etc/bashrc || die "Failed to source bash environment"

# Configure benchmark
case $OPENFOAM_MODEL in
motorbike-default)
	cd tutorials/incompressible/simpleFoam/ || die "Failed to cd to simpleFoam tutorial directory"
	rm -rf motorBike-mmtests
	cp -r motorBike motorBike-mmtests
	cd motorBike-mmtests || die "Failed to cd to motorbike-mmtests tutorial directory"
	###SHELLPACK self_extract motorBike-fvSolution

	# motorBike-snappyHexMeshDic is adapted from
	# tutorials/mesh/snappyHexMesh/motorBike_leakDetection/system/snappyHexMeshDict
	###SHELLPACK self_extract motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_LOCAL_CELLS/$OPENFOAM_LOCAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_GLOBAL_CELLS/$OPENFOAM_GLOBAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_REFINEMENT_CELLS/$OPENFOAM_REFINEMENT_CELLS/"	$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_CELL_LEVELS/$OPENFOAM_CELL_LEVELS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	mv $SHELLPACK_TEMP/motorBike-fvSolution system/fvSolution
	mv $SHELLPACK_TEMP/motorBike-snappyHexMeshDic system/snappyHexMeshDict

	# Leave domains
	SUBDOMAINS=6

	# Patch Allrun to record timing of parallel steps
	###SHELLPACK self_extract Allrun-motorBike.patch
	cat $SHELLPACK_TEMP/Allrun-motorBike.patch | patch -p1 || \
		die "Failed to patch Allrun to record timing of parallel steps"
	;;
motorbike-subdomains)
	cd tutorials/incompressible/simpleFoam/ || die "Failed to cd to simpleFoam tutorial directory"
	rm -rf motorBike-mmtests
	cp -r motorBike motorBike-mmtests
	cd motorBike-mmtests || die "Failed to cd to motorbike-mmtests tutorial directory"
	###SHELLPACK self_extract motorBike-fvSolution

	# motorBike-snappyHexMeshDic is adapted from
	# tutorials/mesh/snappyHexMesh/motorBike_leakDetection/system/snappyHexMeshDict
	###SHELLPACK self_extract motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_LOCAL_CELLS/$OPENFOAM_LOCAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_GLOBAL_CELLS/$OPENFOAM_GLOBAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_REFINEMENT_CELLS/$OPENFOAM_REFINEMENT_CELLS/"	$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_CELL_LEVELS/$OPENFOAM_CELL_LEVELS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	mv $SHELLPACK_TEMP/motorBike-fvSolution system/fvSolution
	mv $SHELLPACK_TEMP/motorBike-snappyHexMeshDic system/snappyHexMeshDict

	SUBDOMAINS=$OPENFOAM_MAXCPUS
	# Starting from SUBDOMAINs, calculate the maximum subdomains
	# allowed while maintaining a 3 to 2 ratio for divisions in
	# the X and Y directions. For example, the default is (3 2)
	# for 6 subdomains. 12 domains require (4 3).
	XDIVISION=4
	YDIVISION=3
	XMAX=$XDIVISION
	YMAX=$YDIVISION

	SCALE=1
	while [ $((XMAX*YMAX)) -le $OPENFOAM_MAXCPUS ]; do
	        XMAX=$((XDIVISION*SCALE))

	        TESTY=`echo "scale=0; $XMAX / $XDIVISION * $YDIVISION" | bc -l`
	        if [ $((TESTY/YDIVISION*XDIVISION)) -ne $XMAX ]; then
	                SCALE=$((SCALE+1))
	                continue
                fi
	        YMAX=$TESTY

	        if [ $((XMAX*YMAX)) -le $OPENFOAM_MAXCPUS ]; then
	                XDIVISION=$XMAX
	                YDIVISION=$YMAX
                fi

	        SCALE=$((SCALE+1))
	done

	SUBDOMAINS=$((XDIVISION*YDIVISION))
	echo Scaling parameters
	echo "o Requested subdomains $OPENFOAM_MAXCPUS"
	echo "o Actual subdomains    $SUBDOMAINS"
	echo "o X division           $XDIVISION"
	echo "o Y division           $YDIVISION"
	echo "$OPENFOAM_MAXCPUS : $SUBDOMAINS : $XDIVISION x $YDIVISION" > $LOGDIR_RESULTS/scaling-parameters

	# Rewrite benchmark parameters
	sed -i -e "s/decomposeParDict.6/decomposeParDict.$SUBDOMAINS/" Allrun
	mv system/decomposeParDict.6 system/decomposeParDict.$SUBDOMAINS
	sed -i -e "s/numberOfSubdomains.*/numberOfSubdomains $SUBDOMAINS;/" 	system/decomposeParDict.$SUBDOMAINS
	sed -i -e "s/^    n .*;/    n ($XDIVISION $YDIVISION 1);/"		system/decomposeParDict.$SUBDOMAINS
	cp system/decomposeParDict.$SUBDOMAINS $LOGDIR_RESULTS

	# Patch Allrun to record timing of parallel steps
	###SHELLPACK self_extract Allrun-motorBike.patch
	cat $SHELLPACK_TEMP/Allrun-motorBike.patch | patch -p1 || \
		die "Failed to patch Allrun to record timing of parallel steps"
	;;
motorbike-custom)
	cd tutorials/incompressible/simpleFoam/ || die "Failed to cd to simpleFoam tutorial directory"
	rm -rf motorBike-mmtests
	cp -r motorBike motorBike-mmtests
	cd motorBike-mmtests || die "Failed to cd to motorbike-mmtests tutorial directory"
	###SHELLPACK self_extract motorBike-fvSolution

	# motorBike-snappyHexMeshDic is adapted from
	# tutorials/mesh/snappyHexMesh/motorBike_leakDetection/system/snappyHexMeshDict
	###SHELLPACK self_extract motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_LOCAL_CELLS/$OPENFOAM_LOCAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_GLOBAL_CELLS/$OPENFOAM_GLOBAL_CELLS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_REFINEMENT_CELLS/$OPENFOAM_REFINEMENT_CELLS/"	$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	sed -i -e "s/OPENFOAM_CELL_LEVELS/$OPENFOAM_CELL_LEVELS/"		$SHELLPACK_TEMP/motorBike-snappyHexMeshDic
	mv $SHELLPACK_TEMP/motorBike-fvSolution system/fvSolution
	mv $SHELLPACK_TEMP/motorBike-snappyHexMeshDic system/snappyHexMeshDict

	XDIVISION=$OPENFOAM_XDIVISION
	YDIVISION=$OPENFOAM_YDIVISION
	ZDIVISION=$OPENFOAM_ZDIVISION
	SUBDOMAINS=$((XDIVISION*YDIVISION*ZDIVISION))
	echo Scaling parameters
	echo "o Actual subdomains    $SUBDOMAINS"
	echo "o X division           $XDIVISION"
	echo "o Y division           $YDIVISION"
	echo "o Z division           $ZDIVISION"
	echo "$OPENFOAM_MAXCPUS : $SUBDOMAINS : $XDIVISION x $YDIVISION" > $LOGDIR_RESULTS/scaling-parameters

	# Rewrite benchmark parameters
	sed -i -e "s/decomposeParDict.6/decomposeParDict.$SUBDOMAINS/" Allrun
	mv system/decomposeParDict.6 system/decomposeParDict.$SUBDOMAINS
	sed -i -e "s/numberOfSubdomains.*/numberOfSubdomains $SUBDOMAINS;/" 	system/decomposeParDict.$SUBDOMAINS
	sed -i -e "s/^    n .*;/    n ($XDIVISION $YDIVISION $ZDIVISION);/"	system/decomposeParDict.$SUBDOMAINS
	cp system/decomposeParDict.$SUBDOMAINS $LOGDIR_RESULTS

	# Patch Allrun to record timing of parallel steps
	###SHELLPACK self_extract Allrun-motorBike.patch
	cat $SHELLPACK_TEMP/Allrun-motorBike.patch | patch -p1 || \
		die "Failed to patch Allrun to record timing of parallel steps"
	;;
*)
	die "Unrecognised model $OPENFOAM_MODEL"
	;;
esac

export FOAM_SIGFPE="false"

log_cmd "./Allrun"
for BIN in snappyHexMesh simpleFoam; do
	log_linkages `find $SHELLPACK_SOURCES/openfoam-$VERSION-installed/platforms -name $BIN`
done

monitor_pre_hook $LOGDIR_RESULTS $OPENFOAM_MODEL
###SHELLPACK iteration_begin $OPENFOAM_ITERATIONS
	echo Executing iteration $ITERATION/$OPENFOAM_ITERATIONS
	./Allclean
	export ITERATION
	$TIME_CMD -o $LOGDIR_RESULTS/openfoam-time.$ITERATION	\
		./Allrun 2>&1 | tee $LOGDIR_RESULTS/openfoam-log.$ITERATION
	gzip $LOGDIR_RESULTS/openfoam-log.$ITERATION

	tar -czf $LOGDIR_RESULTS/openfoam-steplogs-$ITERATION.tar.gz log.*
	if [ "$OPENFOAM_SAVEDATA" = "yes" ]; then
		tar -czf $LOGDIR_RESULTS/openfoam-data-$ITERATION.tar.gz .
	fi
###SHELLPACK iteration_end
monitor_post_hook $LOGDIR_RESULTS $OPENFOAM_MODEL

exit $SHELLPACK_SUCCESS

==== BEGIN motorBike-fvSolution ====
/*--------------------------------*- C++ -*----------------------------------*\
| =========                 |                                                 |
| \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox           |
|  \\    /   O peration     | Version:  v1812                                 |
|   \\  /    A nd           | Web:      www.OpenFOAM.com                      |
|    \\/     M anipulation  |                                                 |
\*---------------------------------------------------------------------------*/
FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      fvSolution;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

solvers
{
    p
    {
        solver          PCG;
        preconditioner  DIC;
        tolerance       1e-06;
        relTol          0.05;
    }

    Phi
    {
        $p;
    }

    U
    {
        solver          smoothSolver;
        smoother        GaussSeidel;
        tolerance       1e-8;
        relTol          0.1;
        nSweeps         1;
    }

    k
    {
        solver          smoothSolver;
        smoother        GaussSeidel;
        tolerance       1e-8;
        relTol          0.1;
        nSweeps         1;
    }

    omega
    {
        solver          smoothSolver;
        smoother        GaussSeidel;
        tolerance       1e-8;
        relTol          0.1;
        nSweeps         1;
    }
}

SIMPLE
{
    nNonOrthogonalCorrectors 0;
    consistent yes;
}

potentialFlow
{
    nNonOrthogonalCorrectors 10;
}

relaxationFactors
{
    equations
    {
        U               0.9;
        k               0.7;
        omega           0.7;
    }
}

cache
{
    grad(U);
}

// ************************************************************************* //
==== END motorBike-fvSolution ====
==== BEGIN motorBike-snappyHexMeshDic ====
/*--------------------------------*- C++ -*----------------------------------*\
| =========                 |                                                 |
| \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox           |
|  \\    /   O peration     | Version:  v1812                                 |
|   \\  /    A nd           | Web:      www.OpenFOAM.com                      |
|    \\/     M anipulation  |                                                 |
\*---------------------------------------------------------------------------*/
FoamFile
{
    version     2.0;
    format      ascii;
    class       dictionary;
    object      snappyHexMeshDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //

// Which of the steps to run
castellatedMesh true;
snap            true;
addLayers       true;


// Geometry. Definition of all surfaces. All surfaces are of class
// searchableSurface.
// Surfaces are used
// - to specify refinement for any mesh cell intersecting it
// - to specify refinement for any mesh cell inside/outside/near
// - to 'snap' the mesh boundary to the surface
geometry
{
    motorBike.obj
    {
        type triSurfaceMesh;
        name motorBike;
    }

    refinementBox
    {
        type box;
        min (-1.0 -0.7 0.0);
        max ( 8.0  0.7 2.5);
    }
};



// Settings for the castellatedMesh generation.
castellatedMeshControls
{

    // Refinement parameters
    // ~~~~~~~~~~~~~~~~~~~~~

    // If local number of cells is >= maxLocalCells on any processor
    // switches from from refinement followed by balancing
    // (current method) to (weighted) balancing before refinement.
    maxLocalCells OPENFOAM_LOCAL_CELLS;

    // Overall cell limit (approximately). Refinement will stop immediately
    // upon reaching this number so a refinement level might not complete.
    // Note that this is the number of cells before removing the part which
    // is not 'visible' from the keepPoint. The final number of cells might
    // actually be a lot less.
    maxGlobalCells OPENFOAM_GLOBAL_CELLS;

    // The surface refinement loop might spend lots of iterations refining just a
    // few cells. This setting will cause refinement to stop if <= minimumRefine
    // are selected for refinement. Note: it will at least do one iteration
    // (unless the number of cells to refine is 0)
    minRefinementCells OPENFOAM_REFINEMENT_CELLS;

    // Allow a certain level of imbalance during refining
    // (since balancing is quite expensive)
    // Expressed as fraction of perfect balance (= overall number of cells /
    // nProcs). 0=balance always.
    maxLoadUnbalance 0.10;


    // Number of buffer layers between different levels.
    // 1 means normal 2:1 refinement restriction, larger means slower
    // refinement.
    nCellsBetweenLevels OPENFOAM_CELL_LEVELS;



    // Explicit feature edge refinement
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    // Specifies a level for any cell intersected by its edges.
    // This is a featureEdgeMesh, read from constant/triSurface for now.
    features
    (
        {
            file "motorBike.eMesh";
            level 6;
        }
    );



    // Surface based refinement
    // ~~~~~~~~~~~~~~~~~~~~~~~~

    // Specifies two levels for every surface. The first is the minimum level,
    // every cell intersecting a surface gets refined up to the minimum level.
    // The second level is the maximum level. Cells that 'see' multiple
    // intersections where the intersections make an
    // angle > resolveFeatureAngle get refined up to the maximum level.

    refinementSurfaces
    {
        motorBike
        {
            // Surface-wise min and max refinement level
            level (5 6);

            // Optional specification of patch type (default is wall). No
            // constraint types (cyclic, symmetry) etc. are allowed.
            patchInfo
            {
                type wall;
                inGroups (motorBikeGroup);
            }
        }
    }

    // Resolve sharp angles
    resolveFeatureAngle 30;


    // Region-wise refinement
    // ~~~~~~~~~~~~~~~~~~~~~~

    // Specifies refinement level for cells in relation to a surface. One of
    // three modes
    // - distance. 'levels' specifies per distance to the surface the
    //   wanted refinement level. The distances need to be specified in
    //   descending order.
    // - inside. 'levels' is only one entry and only the level is used. All
    //   cells inside the surface get refined up to the level. The surface
    //   needs to be closed for this to be possible.
    // - outside. Same but cells outside.

    refinementRegions
    {
        refinementBox
        {
            mode inside;
            levels ((1E15 4));
        }
    }


    // Mesh selection
    // ~~~~~~~~~~~~~~

    // After refinement patches get added for all refinementSurfaces and
    // all cells intersecting the surfaces get put into these patches. The
    // section reachable from the locationInMesh is kept.
    // NOTE: This point should never be on a face, always inside a cell, even
    // after refinement.
    locationInMesh (3.0001 3.0001 0.43);


    // Whether any faceZones (as specified in the refinementSurfaces)
    // are only on the boundary of corresponding cellZones or also allow
    // free-standing zone faces. Not used if there are no faceZones.
    allowFreeStandingZoneFaces true;
}



// Settings for the snapping.
snapControls
{
    //- Number of patch smoothing iterations before finding correspondence
    //  to surface
    nSmoothPatch 3;

    //- Relative distance for points to be attracted by surface feature point
    //  or edge. True distance is this factor times local
    //  maximum edge length.
    tolerance 2.0;

    //- Number of mesh displacement relaxation iterations.
    nSolveIter 30;

    //- Maximum number of snapping relaxation iterations. Should stop
    //  before upon reaching a correct mesh.
    nRelaxIter 5;

    // Feature snapping

        //- Number of feature edge snapping iterations.
        //  Leave out altogether to disable.
        nFeatureSnapIter 10;

        //- Detect (geometric only) features by sampling the surface
        //  (default=false).
        implicitFeatureSnap false;

        //- Use castellatedMeshControls::features (default = true)
        explicitFeatureSnap true;

        //- Detect points on multiple surfaces (only for explicitFeatureSnap)
        multiRegionFeatureSnap false;
}



// Settings for the layer addition.
addLayersControls
{
    // Are the thickness parameters below relative to the undistorted
    // size of the refined cell outside layer (true) or absolute sizes (false).
    relativeSizes true;

    // Per final patch (so not geometry!) the layer information
    layers
    {
        "(lowerWall|motorBike).*"
        {
            nSurfaceLayers 1;
        }
    }

    // Expansion factor for layer mesh
    expansionRatio 1.0;

    // Wanted thickness of final added cell layer. If multiple layers
    // is the thickness of the layer furthest away from the wall.
    // Relative to undistorted size of cell outside layer.
    // See relativeSizes parameter.
    finalLayerThickness 0.3;

    // Minimum thickness of cell layer. If for any reason layer
    // cannot be above minThickness do not add layer.
    // Relative to undistorted size of cell outside layer.
    minThickness 0.1;

    // If points get not extruded do nGrow layers of connected faces that are
    // also not grown. This helps convergence of the layer addition process
    // close to features.
    // Note: changed(corrected) w.r.t 1.7.x! (didn't do anything in 1.7.x)
    nGrow 0;

    // Advanced settings

    // When not to extrude surface. 0 is flat surface, 90 is when two faces
    // are perpendicular
    featureAngle 60;

    // At non-patched sides allow mesh to slip if extrusion direction makes
    // angle larger than slipFeatureAngle.
    slipFeatureAngle 30;

    // Maximum number of snapping relaxation iterations. Should stop
    // before upon reaching a correct mesh.
    nRelaxIter 3;

    // Number of smoothing iterations of surface normals
    nSmoothSurfaceNormals 1;

    // Number of smoothing iterations of interior mesh movement direction
    nSmoothNormals 3;

    // Smooth layer thickness over surface patches
    nSmoothThickness 10;

    // Stop layer growth on highly warped cells
    maxFaceThicknessRatio 0.5;

    // Reduce layer growth where ratio thickness to medial
    // distance is large
    maxThicknessToMedialRatio 0.3;

    // Angle used to pick up medial axis points
    // Note: changed(corrected) w.r.t 1.7.x! 90 degrees corresponds to 130
    // in 1.7.x.
    minMedialAxisAngle 90;


    // Create buffer region for new layer terminations
    nBufferCellsNoExtrude 0;


    // Overall max number of layer addition iterations. The mesher will exit
    // if it reaches this number of iterations; possibly with an illegal
    // mesh.
    nLayerIter 50;
}



// Generic mesh quality settings. At any undoable phase these determine
// where to undo.
meshQualityControls
{
    #include "meshQualityDict"


    // Advanced

    //- Number of error distribution iterations
    nSmoothScale 4;
    //- Amount to scale back displacement at error points
    errorReduction 0.75;
}


// Advanced

// Format to use for lines (e.g. leak path)
setFormat ensight;

// Write flags
writeFlags
(
    scalarLevels
    layerSets
    layerFields     // write volScalarField for layer coverage
);


// Merge tolerance. Is fraction of overall bounding box of initial mesh.
// Note: the write tolerance needs to be higher than this.
mergeTolerance 1e-6;


// ************************************************************************* //
==== END motorBike-snappyHexMeshDic ====

==== BEGIN Allrun-motorBike.patch ====
diff --git a/Allrun b/Allrun
index e0e6038798e6..86305c9b7957 100755
--- a/Allrun
+++ b/Allrun
@@ -9,11 +9,20 @@ decompDict="-decomposeParDict system/decomposeParDict.6"
 
 # copy motorbike surface from resources directory
 \cp $FOAM_TUTORIALS/resources/geometry/motorBike.obj.gz constant/triSurface/
+echo surfaceFeatureExtract:start:`date +%s` > $LOGDIR_RESULTS/step-times.$ITERATION
 runApplication surfaceFeatureExtract
+echo surfaceFeatureExtract:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
 
+echo blockMesh:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runApplication blockMesh
+echo blockMesh:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
 
+echo decomposePar:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runApplication $decompDict decomposePar
+echo decomposePar:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
 
 # Using distributedTriSurfaceMesh?
 if foamDictionary -entry geometry -value system/snappyHexMeshDict | \
@@ -22,7 +31,14 @@ then
     runParallel $decompDict surfaceRedistributePar motorBike.obj independent
 fi
 
+echo snappyHexMesh:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runParallel $decompDict snappyHexMesh -overwrite
+echo snappyHexMesh:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
+
+if [ "$OPENFOAM_STOPAT_MESH" = "yes" ]; then
+	exit 0
+fi
 
 #- For non-parallel running: - set the initial fields
 # restore0Dir
@@ -30,11 +46,23 @@ runParallel $decompDict snappyHexMesh -overwrite
 #- For parallel running: set the initial fields
 restore0Dir -processor
 
+echo patchSummary:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runParallel $decompDict patchSummary
+echo patchSummary:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
+
+echo potentialFoam:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runParallel $decompDict potentialFoam
+echo potentialFoam:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+echo $((ENDTIME-STARTTIME)) > $LOGDIR_RESULTS/step-potentialFoam.$ITERATION
+echo checkMesh:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runParallel $decompDict checkMesh -writeFields '(nonOrthoAngle)' -constant
-
+echo checkMesh:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
+echo simpleFoam:start:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
 runParallel $decompDict $(getApplication)
+echo simpleFoam:end:`date +%s` >> $LOGDIR_RESULTS/step-times.$ITERATION
+
 
 runApplication reconstructParMesh -constant
 runApplication reconstructPar -latestTime
==== END Allrun-motorBike.patch ====
